<script lang="tsx">
import { defineComponent, ref, watch } from 'vue';
import { $t } from '@vben/locales';
import BaseDrawer from '#/components/common/base-drawer.vue';
import UploadFile from './upload-file.vue';
import { getMatchListApi, getGroupListApi, getTrackListApi, createRegistrationInfoApi } from '#/api/competition/registration-info';
import { getTeamInfoPageApi } from '#/api/competition/team-info';

export default defineComponent({
  name: 'AddRegistrationInfo',
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    }
  },
  emits: ['update:modelValue', 'confirm', 'cancel'],
  setup(props, { emit }) {
    const formRef = ref();
    const fileUploadRef = ref();
    const videoUploadRef = ref();
    const visible = ref(false);
    const loading = ref(false);
    const matchList = ref<Array<{ label: string; value: any }>>([]);
    const groupList = ref<Array<{ label: string; value: any }>>([]);
    const trackList = ref<Array<{ label: string; value: any }>>([]);
    const teamList = ref<Array<{ label: string; value: any }>>([]);
    const initFormData = () => {
      return {
        compId: '', // 大赛名称
        groupId: '', // 赛事组别
        trackId: '', // 所属赛题
        teamId: '', // 团队名称
        worksName: '', // 作品名称
        worksIntro: '', // 作品简介
        worksIntroduceFile: undefined, // 作品讲解课件
        videoAssetId: undefined // 作品介绍视频
      }
    }

    // 大赛名称下拉框
    const getMatchList = async () => {
      const res = await getMatchListApi();
      console.log('res', res);
      return res.map((item: any) => ({
        label: item.matchName, // 使用 matchName 字段
        value: item.id
      }));
    }

    // 赛事组别下拉框
    const getGroupList = async () => {
      if (!localFormData.value.compId) {
        return [];
      }
      const params = {
        compId: localFormData.value.compId,
      }
      const res = await getGroupListApi(params);
      console.log('res', res);
      return res.data.map((item: any) => ({
        label: item.name,
        value: item.id
      }));
    }

    // 所属赛题下拉框
    const getTrackList = async () => {
      if (!localFormData.value.compId || !localFormData.value.groupId) {
        return [];
      }
      const res = await getTrackListApi({
        compId: localFormData.value.compId,
        groupId: localFormData.value.groupId,
        curPage: 1,
        releaseStatus: '1'
      });
      console.log('res', res);
      return res.data.map((item: any) => ({
        label: item.name,
        value: item.id
      }));
    }

    // 团队名称下拉框
    const getTeamList = async () => {
      const res = await getTeamInfoPageApi({
        curPage: 1
      });
      console.log('team res', res);
      return res.data.map((item: any) => ({
        label: item.name,
        value: item.id
      }));
    }

    // 表单数据
    const localFormData = ref(initFormData() as Record<string, any>);
    // 基本信息表单配置
    const basicFormColumns = ref([
      {
        prop: 'compId',
        label: $t('competition.registrationInfo.compName'),
        type: 'select',
        placeholder: $t('common.selectPhTxt', [$t('competition.registrationInfo.compName')]),
        required: true,
        get options() {
          return matchList.value;
        },
        onChange: async () => {
          localFormData.value.groupId = '';
          groupList.value = await getGroupList() || [];
        }
      },
      {
        prop: 'groupId',
        label: $t('competition.registrationInfo.groupName'),
        type: 'select',
        class: 'group-form-item',
        placeholder: $t('common.selectPhTxt', [$t('competition.registrationInfo.groupName')]),
        required: true,
        get options() {
          return groupList.value;
        },
        onChange: async () => {
          localFormData.value.trackId = '';
          trackList.value = await getTrackList();
        }
      },
      {
        prop: 'trackId',
        label: $t('competition.registrationInfo.trackName'),
        type: 'select',
        placeholder: $t('common.selectPhTxt', [$t('competition.registrationInfo.trackName')]),
        required: true,
        get options() {
          return trackList.value;
        }
      },
      {
        prop: 'teamId',
        label: $t('competition.teamName'),
        type: 'select',
        class: 'team-form-item',
        placeholder: $t('common.selectPhTxt', [$t('competition.teamName')]),
        required: true,
        get options() {
          return teamList.value;
        }
      },
      {
        prop: 'worksName',
        label: $t('competition.registrationInfo.worksName'),
        type: 'input',
        maxlength: 30,
        showWordLimit: true,
        placeholder: $t('common.inputPhTxt', [$t('competition.registrationInfo.worksName')]),
        required: true,
      },
      {
        prop: 'worksIntro',
        label: $t('competition.registrationInfo.worksIntro'),
        type: 'textarea',
        placeholder: $t('common.inputPhTxt', [$t('competition.registrationInfo.worksIntro')]),
        rows: 5,
        maxlength: 300,
        showWordLimit: true,
        formItemProps: {
          style: {
            width: '100%',
            margin: '0 0 20px 0',
          },
        },
      },
      {
        prop: 'worksIntroduceFile',
        label: $t('competition.registrationInfo.worksIntroduceFile'),
        required: true,
        formItemProps: {
          style: {
            width: '100%',
            margin: '0 0 20px 0',
          },
        },
        render: () => {
          return (
            <div>
              <UploadFile
                ref={fileUploadRef}
                v-model={localFormData.value.worksIntroduceFile}
                onUpdate:modelValue={(value: any) => {
                  console.log('value', value)
                  localFormData.value.worksIntroduceFile = value;
                  // 文件选中后验证字段
                  if (formRef.value) {
                    formRef.value.validateField('worksIntroduceFile');
                  }
                }}
                maxSize={20}
                limit={1}
                listType="text"
                showFileList={true}
                accept=".pdf,.ppt"
                isVideo={false}
                uploadTips={$t('common.fileFormatTip', { type: 'pdf、ppt', size: 20 })}
              />
            </div>

          )
        }
      },
      {
        prop: 'videoAssetId',
        label: $t('competition.registrationInfo.videoAssetId'),
        formItemProps: {
          style: {
            width: '100%',
            margin: '0 0 20px 0',
          },
        },
        render: () => {
          return (
            <div>
              <div class="inline-block text-xs text-gray-400">
                { $t('common.fileFormatTip', { type: 'mp4、mov、webm', size: 20 }) }
              </div>
              <UploadFile
                ref={videoUploadRef}
                v-model={localFormData.value.videoAssetId}
                onUpdate:modelValue={(value: any) => {
                  localFormData.value.videoAssetId = value;
                }}
                maxSize={20}
                limit={1}
                accept=".mp4,.mov,.webm"
                showFileList={true}
                listType="text"
                isVideo={true}
                uploadTips={$t('common.fileFormatTip', { type: 'mp4、mov、webm', size: 20 })}
              />
            </div>
          )
        }
      }
    ]);

    // 表单验证规则
    const formRules = {
      compId: [
        { required: true, message: $t('common.selectPhTxt', [$t('competition.registrationInfo.compName')]), trigger: 'change' }
      ],
      groupId: [
        { required: true, message: $t('common.selectPhTxt', [$t('competition.registrationInfo.groupName')]), trigger: 'change' }
      ],
      trackId: [
        { required: true, message: $t('common.selectPhTxt', [$t('competition.registrationInfo.trackName')]), trigger: 'change' }
      ],
      teamId: [
        { required: true, message: $t('common.selectPhTxt', [$t('competition.teamName')]), trigger: 'change' }
      ],
      worksName: [
        { required: true, message: $t('common.inputPhTxt', [$t('competition.registrationInfo.worksName')]), trigger: 'blur' }
      ],
      worksIntroduceFile: [
        { required: true, message: $t('competition.registrationInfo.worksIntroduceFileTip'), trigger: 'change' }
      ]
    };

    // 监听 modelValue 变化
    watch(() => props.modelValue, async (val) => {
      visible.value = val;
      if (val) {
        // 加载表单中大赛名称，赛事组别，所属赛题的option
        matchList.value = await getMatchList() || [];
        teamList.value = await getTeamList() || [];
      } else {
        initForm();
      }
    }, { deep: true });

    // 处理关闭
    const handleClose = () => {
      initForm();
      emit('update:modelValue', false);
      emit('cancel');
    };

    // 处理确认
    const handleConfirm = async () => {
      if (!formRef.value) return;
      console.log('localFormData.value', localFormData.value);
      try {
        // 表单验证
        const valid = await new Promise((resolve) => {
          formRef.value.validate((isValid: boolean) => {
            resolve(isValid);
          });
        });
        if (!valid) {
          return;
        }
        // 如果有文件需要上传，先上传文件
        try {
          // 上传作品讲解课件
          if (fileUploadRef.value?.uploadToObs) {
            const fileUploadResult = await fileUploadRef.value.uploadToObs();
            if (fileUploadResult) {
              localFormData.value.worksIntroduceFile = fileUploadResult.path;
            }
          }
          
          // 上传视频文件
          if (videoUploadRef.value?.uploadToObs) {
            const videoUploadResult = await videoUploadRef.value.uploadToObs();
            if (videoUploadResult) {
              localFormData.value.videoAssetId = videoUploadResult.path;
            }
          }
        } catch (error) {
          console.error('文件上传失败:', error);
          return;
        }
        loading.value = true;
        createRegistrationInfoApi(localFormData.value as any).then(res => {
          console.log('res', res)
          handleClose();
          emit('confirm', res);
        }).finally(() => {
          loading.value = false;
        })
      } catch (error) {}
    };

    // 更新表单数据
    const handleFormUpdate = (data: any) => {
      localFormData.value = data;
    };

    // 初始化表单数据
    const initForm = () => {
      localFormData.value = initFormData();
    }

    return () => (
      <BaseDrawer
        modelValue={visible.value}
        title={$t('common.newTxt')}
        onUpdate:modelValue={(val: boolean) => emit('update:modelValue', val)}
        onClose={handleClose}
        onConfirm={handleConfirm}
        showFooter={true}
        v-slots={{
          footer: () => (
            <div>
              <el-button onClick={handleClose}>{$t('common.cancelTxt')}</el-button>
              <el-button loading={loading.value} plain type="primary" onClick={() => handleConfirm()}>{$t('common.submitTxt')}</el-button>
            </div>
          )
        }}
      >
        <div class="add-registration-info-container">
          <div class="form-section">
            <div class="section-content">
              <base-form
                ref={formRef}
                columns={basicFormColumns.value}
                modelValue={localFormData.value}
                rules={formRules}
                label-position="right"
                label-width="110px"
                inline={true}
                onUpdate:modelValue={handleFormUpdate}
              />
            </div>
          </div>
        </div>
      </BaseDrawer>
    );
  }
});
</script>

<style lang="scss" scoped>
.add-registration-info-container {
  .form-section {
    .section-content {
      :deep(.base-form-item) {
        margin-bottom: 20px;

        .el-form-item__content {
          width: 100%;
        }
      }

      // 设置宽度不为100%且排列在右边的表单项，margin-right为0
      :deep(.el-form-item:not([style*="width: 100%"])) {
        width: calc((100% - 32px)/2);

        &:nth-of-type(even) {
          margin-right: 0 !important;
        }
      }
    }
  }
}
</style>
